'use strict';

const Service = require('egg').Service;

class ReviewService extends Service {
  // 创建评价
  async createReview(reviewData) {
    const { ctx } = this;
    
    console.log('========== 创建评价 ==========');
    console.log('接收到的数据:', JSON.stringify(reviewData, null, 2));
    
    // 验证必填字段
    if (!reviewData.enterpriseId) {
      throw new Error('企业ID不能为空');
    }
    if (!reviewData.userId) {
      throw new Error('用户ID不能为空');
    }
    if (!reviewData.content || !reviewData.content.trim()) {
      throw new Error('评价内容不能为空');
    }
    if (!reviewData.rating || reviewData.rating < 1 || reviewData.rating > 5) {
      throw new Error('评分必须在1-5之间');
    }
    
    try {
      // 准备创建数据
      const createData = {
        enterpriseId: Number(reviewData.enterpriseId),
        userId: Number(reviewData.userId),
        content: reviewData.content.trim(),
        rating: Number(reviewData.rating),
        userName: reviewData.userName || '匿名用户',
        reviewTime: new Date()
      };
      
      console.log('准备创建的数据:', JSON.stringify(createData, null, 2));
      
      const review = await ctx.model.Review.create(createData);
      
      console.log('评价创建成功:', review.reviewId);
      
      // 更新企业评分
      await this.updateEnterpriseRating(reviewData.enterpriseId);
      
      console.log('========== 创建评价完成 ==========');
      return review;
    } catch (error) {
      console.error('创建评价失败:', error.message);
      console.error('错误堆栈:', error.stack);
      throw new Error(`创建评价失败: ${error.message}`);
    }
  }

  // 更新企业评分
  async updateEnterpriseRating(enterpriseId) {
    const { ctx } = this;
    
    const reviews = await ctx.model.Review.findAll({
      where: { enterpriseId },
      attributes: ['rating']
    });

    if (reviews.length > 0) {
      const avgRating = reviews.reduce((sum, review) => sum + review.rating, 0) / reviews.length;
      
      await ctx.model.Enterprise.update(
        { rating: avgRating },
        { where: { enterpriseId } }
      );
    }
  }

  // 获取企业评价列表
  async getEnterpriseReviews(enterpriseId, { page, pageSize }) {
    const { ctx } = this;
    
    // 确保分页参数为数字类型
    const pageNum = parseInt(page, 10) || 1;
    const pageSizeNum = parseInt(pageSize, 10) || 10;
    
    console.log('获取企业评价列表，参数:', { enterpriseId, pageNum, pageSizeNum });
    
    const { count, rows } = await ctx.model.Review.findAndCountAll({
      where: { enterpriseId: Number(enterpriseId) },
      order: [['reviewTime', 'DESC']],
      limit: pageSizeNum,
      offset: (pageNum - 1) * pageSizeNum
    });

    console.log('查询结果:', { count, rowsCount: rows.length });

    return {
      list: rows,
      total: count,
      page: pageNum,
      pageSize: pageSizeNum
    };
  }

  // 删除评价
  async deleteReview(reviewId) {
    const { ctx } = this;
    
    const review = await ctx.model.Review.findByPk(reviewId);
    if (!review) {
      throw new Error('评价不存在');
    }

    const enterpriseId = review.enterpriseId;
    
    // 删除评价
    await review.destroy();

    // 重新计算企业评分
    await this.updateEnterpriseRating(enterpriseId);

    return { success: true };
  }

  // 回复评价
  async replyReview(reviewId, replyContent) {
    const { ctx } = this;
    
    const review = await ctx.model.Review.findByPk(reviewId);
    if (!review) {
      throw new Error('评价不存在');
    }

    await review.update({
      replyContent,
      replyTime: new Date()
    });

    return review;
  }

  // 举报评价
  async reportReview(reviewId, reportReason) {
    const { ctx } = this;
    
    const review = await ctx.model.Review.findByPk(reviewId);
    if (!review) {
      throw new Error('评价不存在');
    }

    await review.update({
      complaintStatus: 'pending'
    });

    // 这里可以创建举报记录表
    return { success: true };
  }

  // 处理投诉
  async processComplaint(complaintId, processData) {
    const { ctx } = this;
    
    const review = await ctx.model.Review.findByPk(complaintId);
    if (!review) {
      throw new Error('投诉不存在');
    }

    await review.update({
      complaintStatus: processData.processResult,
      replyContent: processData.processNote,
      replyTime: new Date()
    });

    return review;
  }

  // 获取投诉列表
  async getComplaints({ page, pageSize, status }) {
    const { ctx } = this;
    
    // 确保分页参数为数字类型
    const pageNum = parseInt(page, 10) || 1;
    const pageSizeNum = parseInt(pageSize, 10) || 10;
    
    const where = {};
    if (status && status !== 'all') {
      where.complaintStatus = status;
    }

    const { count, rows } = await ctx.model.Review.findAndCountAll({
      where,
      order: [['reviewTime', 'DESC']],
      limit: pageSizeNum,
      offset: (pageNum - 1) * pageSizeNum
    });

    return {
      list: rows,
      total: count,
      page: pageNum,
      pageSize: pageSizeNum
    };
  }
}

module.exports = ReviewService;














